<template>
	<view class='pagesLogin'>
		<view class="img-a">
			<u--image :showLoading="true" src="/static/images/showImg/loginBg.png" width="100%"
				height="480rpx"></u--image>
			<view class="welTitle">
				<view>您好</view>
				<view>欢迎使用皮肤管理小程序</view>
			</view>
		</view>
		<view class="loginContent">
			<view class="t-login">
				<u--form labelPosition="top" :model="loginForm" ref="uForm" labelWidth="160rpx"
					:labelStyle="{color:'#1C2023',fontSize:'32rpx',fontWeight:'bold'}">
					<u-form-item label="账号" prop="username" ref="username">
						<u--input v-model="loginForm.username"></u--input>
					</u-form-item>
					<u-form-item label="密码" prop="password" ref="password">
						<u--input v-model="loginForm.password" @keyup.enter.native="handleLogin"></u--input>
					</u-form-item>

					<!-- <view class="input-item flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
                		<view class="iconfont icon-code icon"></view>
                		<input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码"
                			maxlength="4" />
                		<view class="login-code">
                			<image :src="codeUrl" @click="getCode" class="login-code-img"></image>
                		</view>
                	</view> -->

				</u--form>
				<view class="loginBox">
					<!-- <button class="btn" @click="goRegister">注 册</button> -->
					<button class="btn" @click="handleLogin">登 录</button>
				</view>
				<!-- <view class="loginBox1">
                    <button class="reg" icon="map" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"></button>
                    <span>微信登录</span>
                </view> -->
			</view>
		</view>

	</view>
</template>

<script>
	import {
		LoginApi
	} from '@/api/login-api.js'
	import {
		WXApi
	} from '@/api/system/weixin-api.js'
	import {
		setXcxOpenid,
		setToken
	} from '@/common/auth'
	export default {
		data() {
			return {
				codeUrl: "",
				captchaEnabled: true,
				globalConfig: getApp().globalData.config,
				loginForm: {
					username: "",
					password: "",
				},
				rules: {}
			}
		},
		// created() {
		// 	this.getCode()
		// },
		onShow() {
			//#ifdef H5
			let local = location.href
			if (local.indexOf('/#/')>-1) {
				let id = this.getParam(local, 'hospitalId')
				uni.redirectTo({
					url: '/subPackages/remind/medicalInfo/index?hospitalId=' + id
				})
				return false
			}
			//#endif
		},
		methods: {
			getParam(path, name) {

				var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");

				if (reg.test(path))

					return unescape(RegExp.$2.replace(/\+/g, " "));

				return "";

			},
			async getPhoneNumber(e) {
				const code = e.detail.code
				if (!code) {
					return
				}
				await this.wxLogin(code)
			},
			goRegister() {
				this.$tab.navigateTo(`/subPackages/register/index`)
			},
			// 隐私协议
			handlePrivacy() {
				let site = this.globalConfig.appInfo.agreements[0]
				this.$tab.navigateTo(`/subPackages/common/webview/index?title=${site.title}&url=${site.url}`)
			},
			// 用户协议
			handleUserAgrement() {
				let site = this.globalConfig.appInfo.agreements[1]
				this.$tab.navigateTo(`/subPackages/common/webview/index?title=${site.title}&url=${site.url}`)
			},
			// 获取图形验证码
			async getCode() {
				const {
					code,
					captchaEnabled,
					uuid,
					img
				} = await LoginApi.getCodeImg()
				if (code === 200) {
					this.captchaEnabled = captchaEnabled === undefined ? true : captchaEnabled
					if (this.captchaEnabled) {
						this.codeUrl = 'data:image/gif;base64,' + img
						this.loginForm.uuid = uuid
					}
				}
			},
			// 登录方法
			async handleLogin() {
				if (this.loginForm.username === "") {
					this.$modal.msgError("请输入您的账号")
				} else if (this.loginForm.password === "") {
					this.$modal.msgError("请输入您的密码")
				} else if (this.loginForm.code === "" && this.captchaEnabled) {
					this.$modal.msgError("请输入验证码")
				} else {
					this.$modal.loading("登录中，请耐心等待...")
					this.pwdLogin()
				}
			},
			// 密码登录
			async pwdLogin() {
				const {
					code
				} = await this.$store.dispatch('Login', this.loginForm)
				if (code !== 200) {
					if (this.captchaEnabled) {
						this.getCode()
					}
				}
				this.$modal.closeLoading()
				this.loginSuccess()

			},
			// 登录成功后，处理函数
			async loginSuccess(result) {
				const {
					code
				} = await this.$store.dispatch('GetInfo')
				if (code === 200) {
                    // 设置用户信息
                    this.$store.dispatch("initChat")
					this.$tab.reLaunch('/pages/index/index?token=' + uni.getStorageSync('App-Token'))
				}
			},
			async wxLogin(code) {
				let isSuccess = false
				uni.showModal({
					title: '授权登录',
					content: '是否授权登录微信小程序？',
					success: async () => {
						uni.getUserProfile({
							desc: '登录后可同步数据',
							lang: 'zh_CN',
							success: (infoRes) => {
								//获取code
								uni.login({
									provider: 'weixin',
									success: async (loginRes) => {
										const res = await WXApi.getOpenId(loginRes
											.code, 'weixin', infoRes.iv,
											infoRes
											.encryptedData, code)
										// debugger
										if (res.code === 200) {
											setXcxOpenid(res.openid)
											setToken(res.token)
											await this.loginSuccess()
										}
									},
									fail: function(err) {
										uni.showToast({
											icon: 'none',
											title: '授权失败'
										})
									}
								});
							},
							fail: function(err) {
								uni.showToast({
									icon: 'none',
									title: '授权失败'
								})
							}
						});
					}
				})


				// uni.getUserProfile({
				// 	desc: '123',
				// 	lang: 'zh_CN',
				// 	success: async userRes => {
				// 		console.log(userRes);
				// 		debugger
				// 		const res = await WXApi.getOpenId(loginRes.code)
				// 		console.log(res)

				// 	}
				// })

				// uni.showToast({
				// 	title: '微信登录',
				// 	icon: 'none'
				// });
			},
		}
	}
</script>

<style lang="scss" scoped>
	.pagesLogin {
		// background: $uni-bg-main-color;
		background: #fff;
		min-height: 100vh;

		.img-a {
			position: relative;
			width: 100%;
			height: 450rpx;
			// background-image: url(https://zhoukaiwen.com/img/loginImg/head.png);
			background-size: 100%;

			.welTitle {
				position: absolute;
				left: 24rpx;
				top: 148rpx;
				font-weight: bold;

				:first-child {
					height: 70rpx;
					font-size: 50rpx;
				}

				:nth-child(2) {
					height: 39rpx;
					font-size: 28rpx;
				}


			}

		}


		.loginContent {
			width: 100%;
			position: relative;
			// margin-top: -120rpx;
			background-color: #ffffff;
			border-radius: 8% 8% 0% 0;

			.t-login {
				width: 600rpx;
				margin: 0 auto;
				font-size: 28rpx;
				padding-top: 60rpx;

				.t-a {
					&:nth-child(2) {
						padding-top: 60rpx;
					}

					.txt {
						font-size: 32rpx;
						font-weight: bold;
						color: #333333;
						margin-bottom: 30rpx;
					}

				}


				.loginBox {
					display: flex;
					justify-content: space-between;
					padding-top: 80rpx;

					.btn {
						width: 290rpx;
						font-size: 28rpx;
						background: #49b9ad;
						color: #fff;
						height: 90rpx;
						line-height: 90rpx;
						border-radius: 50rpx;
						font-weight: bold;
						border-radius: 20rpx 20rpx 20rpx 20rpx;
					}
				}

				.loginBox1 {
					display: flex;
					flex-direction: column;
					align-items: center;
					margin-top: 140rpx;

					.reg {
						width: 100rpx;
						height: 100rpx;
						border-radius: 50%;
						// background: #49b9ad;
						background-size: 100rpx 100rpx;
						background-image: url('../static/images/showImg/weixin.png');
					}
				}

			}

		}
	}
</style>